import React, { useRef, useState, useEffect } from "react";
import { Helmet } from "react-helmet";
export default function SmartBGRemover() {
const [fileName, setFileName] = useState("");
const [src, setSrc] = useState(null);
const [resultUrl, setResultUrl] = useState(null);
const [loading, setLoading] = useState(false);
const fileInputRef = useRef(null);
const canvasRef = useRef(null);
useEffect(() => {
document.title = "Smart Background Remover | Free Online Tool - Asad Innovation";
}, []);
const handleFile = async (file) => {
if (!file) return;
setFileName(file.name);
const url = URL.createObjectURL(file);
setSrc(url);
setResultUrl(null);
};
const onDrop = (e) => {
e.preventDefault();
const file = e.dataTransfer.files?.[0];
handleFile(file);
};
const onChooseFile = (e) => {
const file = e.target.files?.[0];
handleFile(file);
};
const removeBackgroundClient = async () => {
if (!src) return;
setLoading(true);
setResultUrl(null);
await new Promise((r) => setTimeout(r, 50));
const img = new Image();
img.crossOrigin = "anonymous";
img.src = src;
img.onload = () => {
const canvas = canvasRef.current;
if (!canvas) {
setLoading(false);
alert("Canvas not available.");
return;
}
canvas.width = img.width;
canvas.height = img.height;
const ctx = canvas.getContext("2d");
if (!ctx) {
setLoading(false);
alert("Context not available.");
return;
}
ctx.drawImage(img, 0, 0);
const imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);
const data = imgData.data;
const bg = [data[0], data[1], data[2]];
const threshold = 60;
for (let i = 0; i < data.length; i += 4) {
const r = data[i], g = data[i + 1], b = data[i + 2];
const dist = Math.sqrt((r - bg[0]) ** 2 + (g - bg[1]) ** 2 + (b - bg[2]) ** 2);
if (dist < threshold) data[i + 3] = 0;
}
ctx.putImageData(imgData, 0, 0);
canvas.toBlob((blob) => {
if (!blob) return setLoading(false);
const urlOut = URL.createObjectURL(blob);
setResultUrl(urlOut);
setLoading(false);
}, "image/png");
};
};
const processImage = async () => {
if (!fileInputRef.current?.files?.[0] && !src) return;
await removeBackgroundClient();
};
const downloadResult = () => {
if (!resultUrl) return;
const a = document.createElement("a");
a.href = resultUrl;
a.download = fileName ? `cutout-${fileName.replace(/\.[^.]+$/, "")}.png` : "cutout.png";
document.body.appendChild(a);
a.click();
a.remove();
};
const clearAll = () => {
setSrc(null);
setResultUrl(null);
setFileName("");
if (fileInputRef.current) fileInputRef.current.value = null;
};
return (
<>
Upload any photo and get a transparent background instantly. Free, fast, and AI-powered.